/**
 * Created by ACER on 2017/4/9.
 */

app.controller("release-task-content", function ($scope, $http) {

    console.log('release-task-content controller is this page now.');

    var token = localStorage.getItem('token');
    var condition = sessionStorage.getItem('condition');
    if (!token) {
        $.alert('请登录后再试', function () {
            location.href = '#login';
        });
        return;
    }

    $scope.taskType = [];
    $scope.taskInfo = {};
    $scope.imgs = [];


    $scope.getSavedCondition = function () {
        var taskStr = sessionStorage.getItem('task-pre-to-create');
        var taskImgsStr = sessionStorage.getItem('task-imgs');
        if (taskStr == null && taskImgsStr == null) {
            $scope.$watch('taskInfo', function () {
                $scope.saveTask();
            }, true);
            if (app.isPlusReady) {
                $scope.taskInfo.positionX = app.addressInfo.coords.latitude;
                $scope.taskInfo.positonY = app.addressInfo.coords.longitude;
                $scope.addressDetail = app.addressInfo.addresses;
            }
            $scope.taskInfo.deadline = new Date();
            $scope.$watch('taskInfo.deadline', function () {
                $scope.taskInfo.taskDeadlineTime = $scope.taskInfo.deadline.getTime();
            }, true);
            $scope.$watch('taskInfo', function () {
                $scope.saveTask();
            }, true);
            $scope.$watch('imgs', function () {
                $scope.saveTask();
            }, true);
            return;
        }
        if (taskStr != null) {
            $scope.taskInfo = JSON.parse(taskStr);
            console.log($scope.taskInfo);
            $scope.taskInfo.deadline = new Date($scope.taskInfo.taskDeadlineTime);
        } else {
            $scope.taskInfo.deadline = new Date();
        }
        if (taskImgsStr != null) {
            $scope.imgs = JSON.parse(taskImgsStr);
        }

        if (app.isPlusReady) {
            $scope.taskInfo.positionX = app.addressInfo.coords.latitude;
            $scope.taskInfo.positonY = app.addressInfo.coords.longitude;
            $scope.addressDetail = app.addressInfo.addresses;
        }
        $scope.$watch('taskInfo.deadline', function () {
            $scope.taskInfo.taskDeadlineTime = $scope.taskInfo.deadline.getTime();
        }, true);
        $scope.$watch('taskInfo', function () {
            $scope.saveTask();
        }, true);
        $scope.$watch('imgs', function () {
            $scope.saveTask();
        }, true);
    };

    $scope.saveTask = function () {
        if ($scope.taskInfo == null && $scope.imgs.length == 0) {
            return;
        }
        if ($scope.taskInfo != null) {
            var taskStr = JSON.stringify($scope.taskInfo);
            sessionStorage.setItem('task-pre-to-create', taskStr);
        }
        if ($scope.imgs.length > 0) {
            var taskImgsStr = JSON.stringify($scope.imgs);
            sessionStorage.setItem('task-imgs', taskImgsStr);
        }

    };

    $scope.getTaskType = function () {
        $http({
            method: 'get',
            url: app.netPath + '/tasks/showAllTaskType'
        }).then(function (res) {
            if (!res.data.error) {
                $scope.taskType = res.data.data;
                console.log($scope.taskType);
            } else {
                $.alert(res.data.msg);
            }
        }, function () {
            $.alert('网络出错');
        })
    };


    $scope.initTask = function () {

        var imgs = [];
        // 将所有图片名放到imgs中，然后转换为json数组
        for (var i = 0; i < $scope.imgs.length; i++) {
            imgs.push($scope.imgs[i].imgName);
        }
        $scope.taskInfo.taskImageAddresses = JSON.stringify(imgs);


        $http({
            method: 'post',
            url: app.netPath + '/tasks/details/create',
            headers: {Authorization: token},
            data: $scope.taskInfo
        }).then(function (res) {
            $.alert(res.data.msg, function () {

                console.log('init over');
                // 链接跳转
            });
            if(!res.data.error){
                $scope.taskInfo = {};
                $scope.imgs = [];
                sessionStorage.removeItem('task-pre-to-create');
                sessionStorage.removeItem('task-imgs');
                $scope.getSavedCondition();
            }
            else{
                var errorCode=res.data.error;
                switch (errorCode){
                    case  102:
                        $.alert('请输入任务内容，联系方式，标题和金额');
                        return ;
                    case 205:
                        $.alert('发布失败，请重试');
                        return ;
                    case 206:
                        $.alert('信息丢失，请重试');
                        return ;
                }
            }
        }, function () {
            $.alert('网络出错');
        })
    };

    //单次提交图片的函数
    //参数为传入的一个文件类型input
    $scope.img_upload = function (files) {

        if (!token) {
            return;
        }

        if (!files || !files[0]) {
            return;
        }

        //规定上传到服务器图片的大小
        var needHeight = 300;
        var needWidth = 300;

        //规定略缩图大小
        var smallWidth = needWidth * 0.33;

        //FileReader用来读取本地文件
        var reader = new FileReader();

        //实例化图片用于被加载在画布上
        var img = new Image();

        //声明一个画布对象，当图片上传成功后添加到数组中便于显示
        var img_obj = {};

        //获取当前时间戳作为画布唯一id
        img_obj.id = new Date().getTime();

        //通过将这个画布对象添加到画布组实现自动显示已上传的图片
        var index = $scope.imgs.push(img_obj) - 1;

        //自动刷新双向绑定，预防双向绑定失效
        $scope.$digest();

        //获取预览画布
        var canvas = document.createElement('canvas');
        canvas.width = needWidth;
        canvas.height = needHeight;


        //控制略缩图大小
        canvas.style.width = smallWidth + 'px';

        var ctx = canvas.getContext("2d");

        //当图片加载完毕执行动作
        reader.onload = function () {

            // 通过 reader.result 来访问生成的 DataURL
            img.src = reader.result;

            img.onload = function () {
                //获取图片的高宽
                var width = img.width;
                var height = img.height;

                //获取需要使用的矩形图片区域
                var real_width = width * needHeight / needWidth > height ? height * needWidth / needHeight : width;
                var real_height = width > height * needWidth / needHeight ? height : width * needHeight / needWidth;

                //console.log('need:'+real_width+' '+real_height);
                //console.log('real:'+width+' '+height);

                //定位使图片居中
                var img_x = (width - real_width) / 2;
                var img_y = (height - real_height) / 2;

                //清除原来画布内容
                ctx.clearRect(0, 0, needWidth, needHeight);

                //在画布上渲染头像预览
                ctx.drawImage(img, img_x, img_y, real_width, real_height, 0, 0, needWidth, needHeight);

                //将画布渲染的图像转换为base64字符串储存在data中
                var data = canvas.toDataURL();

                //发送POST请求
                $http({

                    method: 'post',
                    url: app.netPath + "/users/details/image-upload",
                    headers: {'Authorization': token},
                    data: data

                }).then(function (res) {

                    if (!res.data.error) {

                        //将获得的图片名暂时保存
                        $scope.imgs[index].imgName = res.data.data;

                        //将获取图片名转换为路径用以显示
                        $scope.imgs[index].imgAddress = app.netPath + '/resources/img/' + $scope.imgs[index].imgName;


                    } else {

                        $scope.img_del(index);
                        $.alert('错误代码：' + res.data.error + "," + res.data.mes);
                    }


                }, function () {
                    $scope.img_del(index);
                    $.alert('网络或设置错误');
                })
            };

        };

        $scope.img_del = function (index) {
            //删除制定下标的封面图片
            $scope.imgs.splice(index, 1);
        };

        //加载选中的图片
        reader.readAsDataURL(files[0]);
    };

});

